#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/mman.h>

#define BUFFER_SIZE 5

typedef struct {
    int buffer[BUFFER_SIZE];
    int in;
    int out;
    sem_t empty;
    sem_t full;
    sem_t mutex;
} shared_data_t;

int main() {
    // 打开共享内存
    int shm_fd = shm_open("/my_shm", O_RDWR, 0666);
    shared_data_t *shared_data = (shared_data_t *)mmap(NULL, sizeof(shared_data_t), PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);

    while (1) {
        sem_wait(&(shared_data->full));  // 等待缓冲区非空
        sem_wait(&(shared_data->mutex)); // 加锁

        int data = shared_data->buffer[shared_data->out];
        printf("Consumed: %d\n", data);
        shared_data->out = (shared_data->out + 1) % BUFFER_SIZE;

        sem_post(&(shared_data->mutex)); // 解锁
        sem_post(&(shared_data->empty)); // 增加缓冲区空闲数量

        sleep(2); // 消费数据后等待一段时间
    }

    munmap(shared_data, sizeof(shared_data_t));
    close(shm_fd);

    return 0;
}
